package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.dto.WeixinLoginResponseDTO;
import com.sky.entity.User;
import com.sky.exception.BaseException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {


    private static final String JSCODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        log.info("dto:{}", dto.toString());
        // 调用微信的api获取openid
        Map<String, String> param = new HashMap<>();
        param.put("appid", "wxdfb7e65bc647afaa");
        param.put("secret", "2ec9dc53d545aa2d6b180d27f856a8dc");
        param.put("js_code", dto.getCode());
        param.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(JSCODE2SESSION_URL, param);
        log.info("微信登录返回数据：{}", json);
        // json转dto
        WeixinLoginResponseDTO weixinLoginResponseDTO = JSON.parseObject(json, WeixinLoginResponseDTO.class);
        String openid = weixinLoginResponseDTO.getOpenid();
        log.info("openid：{}", openid);
        if(!StringUtils.hasLength(openid)){
            throw new BaseException(MessageConstant.LOGIN_FAILED);
        }
        // 把openid保存到数据据
        // 根据openid查询数据库，判断是否是首次登陆，如果是首次登陆就insert
        User user = userMapper.selectByOpenid(openid);
        if(user == null){
            //是否是首次登陆
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
            log.info("微信用户保存到数据据库：{}", openid);
        }
        // 生成jwt token
        Map<String, Object> payload = new HashMap<>();
        // 如果是首次登录，insert之后需要返回自增的主键
        payload.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), payload);
        // 组装数据
        UserLoginVO vo = new UserLoginVO();
        vo.setOpenid(openid);
        vo.setId(user.getId());
        vo.setToken(token);
        return vo;
    }

    @Override
    public User getById(Long userId) {
        return  userMapper.getById(userId);
    }
}
